package com.shinhye.elephantsafe;

import java.util.ArrayList;
import java.util.List;

import com.shinhye.elephantsafe.db.dao.AntiVirusDao;
import com.shinhye.elephantsafe.domain.ScanInfo;
import com.shinhye.elephantsafe.utils.MD5Utils;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AntiVirusActivity extends Activity {
	private final int MSG_SCANING = 0x001;
	private final int MSG_PAUSE = 0x002;
	private final int MSG_STOP = 0x003;
	private final int MSG_FINISH = 0x005;
	private final int FLAG_START = 0;
	private final int FLAG_SCAN = 1;
	private final int FLAG_PAUSE = 2;
	private final int FLAG_STOP = 4;
	private final String TAG = "AntiVirusActivity";
	
	private ImageView iv_scan_act;
	private TextView tv_scan_status;
	private TextView tv_antivirus_progress;
	private ProgressBar pb_antivirus_progress;
	private LinearLayout ll_scan_progress;
	private Drawable ic_fail;
	private Drawable ic_ok;
	private List<ScanInfo> virusList;
	private TextView tv_scan_res;
	private LinearLayout ll_scanning_bar;
	private Button btn_killvirus;
	private int progress;
	private int flag;
	private Button btn_startpause;
	private PackageManager pm;
	private List<PackageInfo> packInfos;
	
	/*
	 * 如果主线程更新界面，同时Handler接受子线程发送消息也更新界面，可能会出现更新界面先后顺序的问题。
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
			case MSG_SCANING:
				ScanInfo info = (ScanInfo) msg.obj;
				tv_antivirus_progress.setText("正在扫描中...");
				TextView tv_new = new TextView(AntiVirusActivity.this);
				tv_new.setSingleLine();
				tv_new.setText("\t" + info.getAppname());
				tv_scan_res.setText("已扫描" + progress + "个软件");
				if(info.isVirus()) {
					tv_scan_status.setText("危险");
					tv_scan_status.setTextColor(Color.RED);
					tv_new.setCompoundDrawables(ic_fail, null, null, null);
					tv_new.setTextColor(Color.RED);
				} else {
					tv_new.setCompoundDrawables(ic_ok, null, null, null);
				}
				
				ll_scan_progress.addView(tv_new, 0);
				break;
			case MSG_PAUSE:
				tv_antivirus_progress.setText("扫描已暂停");
				iv_scan_act.clearAnimation();

				break;
			case MSG_FINISH:
				Log.i(TAG, "扫描完成！");
				
				iv_scan_act.clearAnimation();
				tv_antivirus_progress.setText("扫描已完成");
				btn_killvirus.setVisibility(View.VISIBLE);
				ll_scanning_bar.setVisibility(View.INVISIBLE);
				if(virusList.size() == 0) {
					btn_killvirus.setEnabled(false);
					btn_killvirus.setTextColor(0xffcccccc);
					tv_scan_res.setText("已扫描" + progress + "个软件，您的手机处于安全状态！");
				} else {
					tv_scan_res.setText("已扫描" + progress + "个软件，共查找到" + virusList.size() + "个病毒！");
				}
				break;
			case MSG_STOP:
				Log.i(TAG, "停止扫描！");
				
				ll_scanning_bar.setVisibility(View.INVISIBLE);
				btn_goback.setVisibility(View.VISIBLE);
				pb_antivirus_progress.setProgress(0);
				tv_antivirus_progress.setText("扫描已终止");
				iv_scan_act.clearAnimation();
				
				break;
			}
		};
	};
	private Button btn_goback;
	private Animation anim;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_antivirus);
		ic_fail = getResources().getDrawable(R.drawable.ic_fail);
		ic_fail.setBounds(0, 0, 20, 20);
		ic_ok = getResources().getDrawable(R.drawable.ic_ok);
		ic_ok.setBounds(0, 0, 20, 20);
		
		tv_scan_res = (TextView) findViewById(R.id.tv_scan_res);
		iv_scan_act = (ImageView) findViewById(R.id.iv_scan_act);
		tv_scan_status = (TextView) findViewById(R.id.tv_scan_status);
		tv_antivirus_progress = (TextView) findViewById(R.id.tv_antivirus_progress);
		pb_antivirus_progress = (ProgressBar) findViewById(R.id.pb_antivirus_progress);
		ll_scan_progress = (LinearLayout) findViewById(R.id.ll_scan_progress);
		ll_scanning_bar = (LinearLayout) findViewById(R.id.ll_scanning_bar);
		btn_killvirus = (Button) findViewById(R.id.btn_killvirus);
		btn_startpause = (Button) findViewById(R.id.btn_startpause);
		btn_goback = (Button) findViewById(R.id.btn_goback);
		
		anim = AnimationUtils.loadAnimation(this, R.anim.rotate_scan_antivirus);
		iv_scan_act.startAnimation(anim);
		
		progress = 0;
		virusList = new ArrayList<ScanInfo>();
		flag = FLAG_START;
		runMain();
	}

	/**
	 * Setup data.
	 */
	private void runMain() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if(flag == FLAG_START) {
					Log.i(TAG, "启动引擎！");
					SystemClock.sleep(600);
					
					pm = getPackageManager();
					packInfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES|PackageManager.GET_SIGNATURES);
					pb_antivirus_progress.setMax(packInfos.size());
				}
				Log.i(TAG, "扫描开始！");
				scan();
				
				if(flag != FLAG_PAUSE && flag != FLAG_STOP) {
					handler.sendEmptyMessage(MSG_FINISH);
				}
			}

		}).start();
	}
	
	/**
	 * A scan operation running in the sub-thread.
	 */
	private void scan() {
		for(int i = progress; i < packInfos.size(); i++) {
			if(flag == FLAG_SCAN || flag == FLAG_START) {
				PackageInfo info = packInfos.get(i);
				String signStr = info.signatures[0].toCharsString();
				String md5 = MD5Utils.md5(signStr);
				ScanInfo scanInfo = AntiVirusDao.virusQuery(md5);
				scanInfo.setAppname(info.applicationInfo.loadLabel(pm).toString());
				
				scanInfo.setIcon(info.applicationInfo.loadIcon(pm));
				scanInfo.setPackname(info.packageName);
				if(scanInfo.getDesc() != null) {
					scanInfo.setVirus(true);
					virusList.add(scanInfo);
				} else {
					scanInfo.setVirus(false);
				}
				
				progress++;
				pb_antivirus_progress.setProgress(progress);
				
				Message msg = handler.obtainMessage();
				msg.what = MSG_SCANING;
				msg.obj = scanInfo;
				handler.sendMessage(msg);
			} else if(flag == FLAG_PAUSE) {
				handler.sendEmptyMessage(MSG_PAUSE);
				return;
			} else if(flag == FLAG_STOP) {
				handler.sendEmptyMessage(MSG_STOP);
				return;
			}
		}
	}
	
	public void pauseorstart(View v) {
		if(flag == FLAG_SCAN || flag == FLAG_START) {
			Log.i(TAG, "暂停扫描！");
			flag = FLAG_PAUSE;
			btn_startpause.setText("继续");
		} else {
			Log.i(TAG, "继续扫描！");
			flag = FLAG_SCAN;
			iv_scan_act.startAnimation(anim);
			btn_startpause.setText("暂停");
			
			runMain();
		}
	}
	
	public void stop(View v) {
		if(flag == FLAG_SCAN || flag == FLAG_START) {
			flag = FLAG_STOP;
		} else {
			handler.sendEmptyMessage(MSG_STOP);
		}
	}
	
	public void killvirus(View v) {
		Log.i(TAG, "处理病毒！");
		
		for(ScanInfo info : virusList) {
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_DELETE);
			intent.setData(Uri.parse("package:" + info.getPackname()));
			startActivityForResult(intent, 101);
		}
	}
	
	public void goback(View v) {
		finish();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		flag = FLAG_STOP;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 101) {
			tv_scan_status.setText("安全");
			tv_scan_status.setTextColor(0xFF00FF00);
			tv_scan_res.setText("您的手机正处于安全状态！");
			btn_goback.setVisibility(View.VISIBLE);
			btn_killvirus.setVisibility(View.INVISIBLE);
		}
	}
}
